﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using HandyControl.Controls;
using Prism.Commands;
using Quartz;

namespace ZYing.QPanel.ViewModels
{
    public class JobExecutionItemViewModel : ViewModelBase
    {
        public IScheduler Scheduler { get; }

        public JobExecutionItemViewModel(IScheduler scheduler, IJobExecutionContext jobExecutionContext)
        {
            Scheduler = scheduler;
            JobExecutionContext = jobExecutionContext;
            InterruptCommand = new DelegateCommand(this.Interrupt);
        }

        public IJobExecutionContext JobExecutionContext { get; }
        public string Id => this.JobExecutionContext.FireInstanceId;
        public JobKey JobKey => this.JobExecutionContext.JobDetail.Key;
        public TriggerKey TriggerKey => this.JobExecutionContext.Trigger.Key;
        public DateTimeOffset? ScheduledFireTime => this.JobExecutionContext.ScheduledFireTimeUtc;
        public DateTimeOffset ActualFireTime => this.JobExecutionContext.FireTimeUtc;
        private TimeSpan _runTime;

        public TimeSpan RunTime
        {
            get { return _runTime; }
            set { SetProperty(ref _runTime, value); }
        }

        private string _status;

        public string Status
        {
            get { return _status; }
            set { SetProperty(ref _status, value); }
        }
        public async void Interrupt()
        {
            if (Helpers.MessageHelper.Confirm("确定要打断该任务的执行吗？"))
            {
                var ret = await this.Scheduler.Interrupt(this.Id);
                if (ret) Helpers.NotifyHelper.Success($"任务打断成功，ID：{this.Id}");
            }
        }
        public DelegateCommand InterruptCommand { get; }

        public async Task RefreshStatus(IJobExecutionContext context)
        {
            this.RunTime = context.JobRunTime;
            if (this.Scheduler.Context.TryGetExecutionHistoryStore(out var historyStore))
            {
                //todo: load history
                var log = await historyStore.FindLastLog(this.JobKey, this.Id);
                if (log != null)
                {
                    this.Status = log.Status;
                }
                else
                {
                    this.Status = String.Empty;
                }
            }
        }
    }
}
